{% extends'base.html' %}
{% block title %}AI智能助手{% endblock %}
{% block nav %}AI智能助手{% endblock %}

{% block Sidebar %}
    <div class="sidebar" data-color="orange">
        <div class="logo">
            <a href="#" class="simple-text logo-mini">
                <img src="../static/assets/img/taobaologo.png" alt="#"/>
            </a>
            <a href="#" class="simple-text logo-normal">
                电商平台用户行为预测系统
            </a>
        </div>
        <div class="sidebar-wrapper">
            <ul class="nav">
                <li>
                    <a href="{{ url_for('ec.index') }}">
                        <i class="now-ui-icons design_app"></i>
                        <p>仪表盘</p>
                    </a>
                </li>
                <li>
                    <a href="{{ url_for('ec.raw_data') }}">
                        <i class="now-ui-icons business_chart-pie-36"></i>
                        <p>原始数据</p>
                    </a>
                </li>
                <li>
                    <a href="{{ url_for('ec.visual2') }}">
                        <i class="now-ui-icons education_atom"></i>
                        <p>预测与推荐</p>
                    </a>
                </li>
                <li>
                    <a href="{{ url_for('ec.visual') }}">
                        <i class="now-ui-icons files_single-copy-04"></i>
                        <p>操作日志</p>
                    </a>
                </li>
                <li>
                    <a href="{{ url_for('ec.user') }}">
                        <i class="now-ui-icons users_single-02"></i>
                        <p>个人中心</p>
                    </a>
                </li>
            </ul>
        </div>
    </div>
{% endblock %}

{% block content %}
    <div class="panel-header panel-header-sm"
         style="background: linear-gradient(135deg, #F5F5F5 0%, #1c84fc 100%);"></div>
    <div class="content">
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card card-chat">
                    <div class="card-header">
                        <div class="d-flex align-items-center">
                            <div class="avatar me-3">
                                <img src="../static/assets/img/ai-avatar.png" alt="AI头像"
                                     class="avatar-img rounded-circle">
                            </div>
                            <div>
                                <h4 class="card-title mb-0">AI智能助手</h4>
                                <p class="text-muted mb-0">电商数据分析与业务咨询专家</p>
                            </div>
                            <div class="ms-auto">
                                <button id="clear-chat" class="btn btn-sm btn-outline-secondary">
                                    <i class="now-ui-icons ui-1_simple-remove"></i> 清空对话
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-0 d-flex flex-column" style="min-height: 300px;">
                        <div id="chat-messages" class="chat-messages flex-grow-1">
                            <div class="message ai-message">
                                <div class="message-avatar">
                                    <img src="../static/assets/img/ai-avatar.png" alt="AI头像">
                                </div>
                                <div class="message-content">
                                    <div class="message-text">
                                        您好！我是电商平台AI助手，可以为您解答关于用户行为分析、商品推荐、数据可视化等问题。请问有什么可以帮您？
                                    </div>
                                    <div class="message-time">{{ now|datetimeformat('%H:%M') }}</div>
                                </div>
                            </div>
                        </div>
                        <div class="chat-input-container mt-auto">
                            <form id="ai-form" class="d-flex">
                                <input type="text" id="ai-input" class="form-control chat-input"
                                       placeholder="输入您的问题..." autocomplete="off" autofocus>
                                <button type="submit" class="btn btn-primary btn-round ml-2 send-button">
                                    <i class="now-ui-icons ui-1_send"></i>
                                </button>
                            </form>
                            <div class="suggestions mt-2">
                                <small class="text-muted">快捷提问:</small>
                                <button class="btn btn-sm btn-outline-primary suggestion-btn">如何提高转化率?</button>
                                <button class="btn btn-sm btn-outline-primary suggestion-btn">热门商品有哪些?</button>
                                <button class="btn btn-sm btn-outline-primary suggestion-btn">用户行为分析</button>
                                <button class="btn btn-sm btn-outline-primary suggestion-btn">购买转化路径</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block css %}
    <link href="../static/assets/css/awswer.css" rel="stylesheet"/>
{% endblock %}

{% block js %}
    <script>
        $(document).ready(function () {
            // 初始化聊天界面
            initChat();

            // 获取 URL 中的问题参数
            const urlParams = new URLSearchParams(window.location.search);
            const question = urlParams.get('question');

            if (question) {
                // 显示用户问题
                addUserMessage(question);
                // 调用 AI 接口获取回答
                fetchAnswer(question);
            }

            // 快捷提问按钮点击事件
            $('.suggestion-btn').click(function (e) {
                e.preventDefault();
                const question = $(this).text();
                $('#ai-input').val(question);
                $('#ai-form').submit();
            });

            // 清空聊天记录
            $('#clear-chat').click(function () {
                $('#chat-messages').html(`
                <div class="message ai-message">
                    <div class="message-avatar">
                        <img src="../static/assets/img/ai-avatar.png" alt="AI头像">
                    </div>
                    <div class="message-content">
                        <div class="message-text">您好！我是电商平台AI助手，可以为您解答关于用户行为分析、商品推荐、数据可视化等问题。请问有什么可以帮您？</div>
                        <div class="message-time">${getCurrentTime()}</div>
                    </div>
                </div>
            `);
            });
        });

        function initChat() {
            // 恢复之前的聊天记录（如果有）
            const savedChat = localStorage.getItem('ai_chat_history');
            if (savedChat) {
                $('#chat-messages').html(savedChat);
                scrollToBottom();
            }
        }

        // 添加用户消息到聊天界面
        function addUserMessage(message) {
            const chatMessages = $('#chat-messages');
            const timeString = getCurrentTime();

            // 直接使用用户头像URL，不显示本地头像
            const userAvatar = "{{ user.avatar_url }}";

            const messageHtml = `
            <div class="message user-message">
                <div class="message-content">
                    <div class="message-text">${escapeHtml(message)}</div>
                    <div class="message-time">${timeString}</div>
                </div>
                <div class="message-avatar">
                    <img src="${userAvatar}" alt="用户头像">
                </div>
            </div>
        `;

            chatMessages.append(messageHtml);
            scrollToBottom();
            saveChatHistory();
        }

        // 添加AI消息到聊天界面
        function addAiMessage(message) {
            const chatMessages = $('#chat-messages');
            const timeString = getCurrentTime();

            const messageHtml = `
            <div class="message ai-message">
                <div class="message-avatar">
                    <img src="../static/assets/img/ai-avatar.png" alt="AI头像">
                </div>
                <div class="message-content">
                    <div class="message-text">${message}</div>
                    <div class="message-time">${timeString}</div>
                </div>
            </div>
        `;

            chatMessages.append(messageHtml);
            scrollToBottom();
            saveChatHistory();
        }

        // 调用AI接口获取答案
        function fetchAnswer(question) {
            // 显示加载状态
            const chatMessages = $('#chat-messages');
            chatMessages.append(`
            <div class="message ai-message">
                <div class="message-avatar">
                    <img src="../static/assets/img/ai-avatar.png" alt="AI头像">
                </div>
                <div class="message-content">
                    <div class="message-text typing-indicator">
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                </div>
            </div>
        `);
            scrollToBottom();

            // 调用 AI 接口获取回答
            fetch('/get_answer', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({question: question}),
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    // 移除加载状态
                    $('.typing-indicator').closest('.message').remove();

                    if (data.answer) {
                        addAiMessage(data.answer);
                    } else if (data.error) {
                        addAiMessage(`抱歉，处理您的请求时出现了问题。<br><small>${escapeHtml(data.error)}</small>`);
                    } else {
                        addAiMessage('未能获取到回答，请稍后再试。');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    // 移除加载状态
                    $('.typing-indicator').closest('.message').remove();
                    addAiMessage(`抱歉，处理您的请求时出现了问题。<br><small>${escapeHtml(error.message)}</small>`);
                });
        }

        // 表单提交事件处理
        $('#ai-form').on('submit', function (event) {
            event.preventDefault();
            const userInput = $('#ai-input').val().trim();

            if (userInput === '') {
                return;
            }

            // 添加用户消息
            addUserMessage(userInput);

            // 清空输入框并保持焦点
            $('#ai-input').val('').focus();

            // 获取AI回答
            fetchAnswer(userInput);
        });

        // 辅助函数：获取当前时间
        function getCurrentTime() {
            const now = new Date();
            return now.getHours() + ':' + (now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes());
        }

        // 辅助函数：滚动到底部
        function scrollToBottom() {
            const chatMessages = $('#chat-messages');
            chatMessages.stop().animate({
                scrollTop: chatMessages[0].scrollHeight
            }, 300);
        }

        // 辅助函数：HTML转义
        function escapeHtml(unsafe) {
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // 保存聊天记录到本地存储
        function saveChatHistory() {
            const chatHtml = $('#chat-messages').html();
            localStorage.setItem('ai_chat_history', chatHtml);
        }

        // 输入框回车键提交
        $('#ai-input').keypress(function (e) {
            if (e.which === 13 && !e.shiftKey) {
                e.preventDefault();
                $('#ai-form').submit();
            }
        });

    </script>
{% endblock %}